import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inner_drawer/inner_drawer.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../bean/alarm_bean.dart';
import '../../common/custom_icons.dart';
import '../../common/data_source.dart';
import '../../common/system_config.dart';
import '../../model/initapp_model.dart';
import '../../pages/selectionarea_view/componets/row_item.dart';
import '../../pages/selectionarea_view/componets/row_itemStatus.dart';
import '../../utils/tools/analysis_code.dart';
import '../../utils/tools/localstorage_tool.dart';
import '../../utils/tools/screenutil_tool.dart';
import '../../utils/tools/timeformat_tool.dart';
import '../../utils/tools/timezerocomplement_tool.dart';
import '../../utils/widget/appbar_widget.dart';
import '../../utils/widget/fixedtip_widget.dart';
import '../../utils/widget/nodata_widget.dart';
import '../../utils/widget/picker_widget.dart';
import '../../utils/widget/toast_widget.dart';
import '../../viewmodel/alarm_vm.dart';
import '../../viewmodel/optiontype_vm.dart';
import 'components/down_boxstyle.dart';
import 'components/load_statedesc.dart';
import 'components/title_positioned.dart';
import 'methods/contrast.dart';
import 'methods/toggle.dart';

class AlarmView extends StatefulWidget {
  @override
  AlarmViewState createState() => new AlarmViewState();
}

class AlarmViewState extends State<AlarmView> {
//  @override
//  bool get wantKeepAlive => true;

  //申明上拉加载更多的状态
  RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );

  // 主题信息
  bool themeInfo = false;

  //存储选择的开始时间，*用于选择最小的结束时间
  PDuration endminDate;

  //数据加载结束开关
  bool falg = true;

  // 页面是否完成加载
  bool isCompleteLoad = false;

  // 台区信息
  Map equipmentInfo;

  // 服务端响应的数据
  List<AlarmModuleItem> pageData = [];

  // 网络状态
  bool networkstate = true;

  // 标记当前app的状态（特指：异常情况0：网络异常  1：WebSocket已断开   2：重连WebSocket）
  int componentState;

  // * 统计各项函数被执行的次数
  // 1、网络监听首次进入页面时为：false（无法网络是否通畅），将为执行未接通的“行为处理”。
  //   因WebSocket中有重连机制，当网络转为正常时会导致拿到数据且不断尝试重连的bug
  // 2、网络监听在builder函数中会被多次触发，但已有的函数都只需要执行一次。
  // 综上所属需要对组件执行次数进行统计并作为判断条件
  int implementCount = 0;

  // 请求参数
  Map<String, dynamic> par = {
    "sourceId": "", // 来源ID
    "equipmentId": "", //台区id（必填）
    "equipmentPositionId": "", //设备位点ID
    "createTimeStart": "", //开始时间
    "createTimeEnd": "", //结束时间
    "status": "0", // 未处理
    "type": null, // 设备类型
    "alarmType": null, //告警类型
    "page": 1, // 页码
    "rows": 50, // 条数
  };

  // 存储“设备类型”选中的数据
  String selectDeviceType = "全部";

  // 存储“告警状态”选中的数据
  String selectAlarmStatus = "全部";

  // 存储“处理状态”选中的数据
  String selectHandleStatus = "未处理";

  // 告警类型基础数据
  List alarmType;

  // 设备类型基础数据
  List deviceType;

  @override
  void initState() {
    super.initState();

    //print("alarm 被初始化了1111");

    // 赋值初始化请求条件
    Contrast.initContrast(par);

    // 初始化主题
    initThemeType();
  }

  @override
  Widget build(BuildContext context) {
//    super.build(context);

    // 当前的系统时间
    Map currentTime = TimeFormat.pickersTimeFormat();
    return Consumer<InitAppModel>(builder: (context, model, child) {
      // 将网络状态存储为全局状态，便于其他函数访问。（该状态会实时更新）
      networkstate = model.networkstate;

      // 必须保证网络通畅
      if (networkstate) {
        // 标记网络已恢复
        componentState = null;

        // 检查是否为初始化状态
        if (implementCount <= 0) {
          // 清空的原有的内容
          pageData = [];
          par["page"] = 1;

          // 发起网络请求，获取页面数据
          initPage(context, isShowLoading: true);
          //print("alarm 被初始化了2222");
          // 统计执行次数
          implementCount++;
        }
      } else {
        // 标记网络异常
        componentState = 0;

        if (implementCount > 0) {
          // 还原组件初始化状态
          implementCount = 0;
        }
      }

      // 绘制组件
      return InnerDrawer(
        key: CreateInnerDrawerKey.innerDrawerKey,
        onTapClose: true, // default false
        swipe: networkstate ? true : false, // default true
        backgroundDecoration: BoxDecoration(color: Colors.black12),
        offset: IDOffset.only(bottom: 0.00, right: 0.4, left: 0.0),
        scale: IDOffset.horizontal(1.0),
        proportionalChildArea: true,
        borderRadius: 0,
        rightAnimationType: InnerDrawerAnimation.quadratic,
        rightChild: Container(
          decoration: BoxDecoration(
              color: themeInfo ? SystemConfig.grayColor : Colors.white,
              boxShadow: [
                BoxShadow(
                    offset: Offset(2, 1), //x,y轴
                    color: Colors.black,
                    blurRadius: 12)
              ]),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: ST.seth(80)),
              Container(
                padding: EdgeInsets.only(left: ST.setw(26)),
                margin: EdgeInsets.only(bottom: ST.seth(30)),
                child: Text("请输入查询条件",
                    style: TextStyle(fontSize: SystemConfig.fs_title1),
                    textAlign: TextAlign.left),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ST.setw(30), vertical: ST.seth(10)),
                child: Row(
                  children: [
                    Text("开始时间：",
                        style: TextStyle(fontSize: SystemConfig.fs_content3)),
                    Expanded(
                      child: InkWell(
                        onTap: () async {
                          PickerWidget.showNewDatePicker(
                            context,
                            mode: DateMode.YMDHMS,
                            pickerStyle:
                                DownBoxStyle(themeInfo, "开始时间").builder(),
                            selectDate: PDuration(
                                year: currentTime["year"],
                                month: currentTime["month"],
                                day: currentTime["day"],
                                hour: currentTime["hour"],
                                minute: currentTime["minute"],
                                second: currentTime["second"]),
                            onConfirm: (PDuration p) {
                              setState(() {
                                endminDate = p;
                                par['createTimeStart'] =
                                    TimeZeroComplement(p).format();
                              });
                            },
                            onChanged: (PDuration p) {
                              // 当开始时间进行修改时，必须清空结束时间。
                              // 该操作为防止结束时间<开始时间
                              if (par['createTimeEnd'] != '') {
                                setState(() {
                                  par['createTimeEnd'] = '';
                                });
                              }
                            },
                          );
                        },
                        child: Container(
                          alignment: Alignment.centerLeft,
                          padding: EdgeInsets.symmetric(
                              horizontal: ST.setw(10), vertical: ST.seth(15)),
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                              border: Border.all(
                                  color: SystemConfig.borderColor,
                                  width: 1,
                                  style: BorderStyle.solid)),
                          child: Text(
                              par["createTimeStart"] == ""
                                  ? "请选择开始时间"
                                  : par["createTimeStart"],
                              style:
                                  TextStyle(fontSize: SystemConfig.fs_Xsmall)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ST.setw(30), vertical: ST.seth(10)),
                child: Row(
                  children: [
                    Text("结束时间：",
                        style: TextStyle(fontSize: SystemConfig.fs_content3)),
                    Expanded(
                      child: InkWell(
                        onTap: () async {
                          // 必须选择了开始时间才能选择结束时间
                          if (par["createTimeStart"] == "") {
                            ToastWidget.toast("必须先选择开始时间");
                          } else {
                            PickerWidget.showNewDatePicker(
                              context,
                              mode: DateMode.YMDHMS,
                              pickerStyle:
                                  DownBoxStyle(themeInfo, "结束时间").builder(),
                              selectDate: PDuration(
                                  year: currentTime["year"],
                                  month: currentTime["month"],
                                  day: currentTime["day"],
                                  hour: currentTime["hour"],
                                  minute: currentTime["minute"],
                                  second: currentTime["second"]),
                              //minDate: endminDate,
                              onConfirm: (p) {
                                bool _r = Comparable.compare(
                                        TimeZeroComplement(p).format(),
                                        par["createTimeStart"]) <
                                    0;

                                if (_r) {
                                  ToastWidget.toast("不可小于开始时间");
                                } else {
                                  setState(() {
                                    par["createTimeEnd"] =
                                        TimeZeroComplement(p).format();
                                  });
                                }
                              },
                            );
                          }
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: ST.setw(10), vertical: ST.seth(15)),
                            alignment: Alignment.centerLeft,
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(2)),
                                border: Border.all(
                                    color: SystemConfig.borderColor,
                                    width: 1,
                                    style: BorderStyle.solid)),
                            child: Text(
                                par["createTimeEnd"] == ""
                                    ? "请选择结束时间"
                                    : par["createTimeEnd"],
                                style: TextStyle(
                                    fontSize: SystemConfig.fs_Xsmall))),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ST.setw(30), vertical: ST.seth(10)),
                child: Row(
                  children: [
                    Text("设备类型：",
                        style: TextStyle(fontSize: SystemConfig.fs_content3)),
                    Expanded(
                      child: InkWell(
                        onTap: () async {
                          PickerWidget.showNewSinglePicker(context,
                              data: deviceType != null ? deviceType : [],
                              selectData: selectDeviceType,
                              pickerStyle: DownBoxStyle(themeInfo, "设备类型")
                                  .builder(), onConfirm: (p) {
                            setState(() {
                              selectDeviceType = p['name'];
                              par["type"] = p["code"] >= 999 ? "" : p["code"];
                            });
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: ST.setw(10), vertical: ST.seth(15)),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                              border: Border.all(
                                  color: SystemConfig.borderColor,
                                  width: 1,
                                  style: BorderStyle.solid)),
                          child: Text(
                              "${selectDeviceType == null ? "请选择设备类型" : selectDeviceType}",
                              style:
                                  TextStyle(fontSize: SystemConfig.fs_Xsmall)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ST.setw(30), vertical: ST.seth(10)),
                child: Row(
                  children: [
                    Text("告警类型：",
                        style: TextStyle(fontSize: SystemConfig.fs_content3)),
                    Expanded(
                      child: InkWell(
                        onTap: () async {
                          PickerWidget.showNewSinglePicker(context,
                              data: alarmType != null ? alarmType : [],
                              selectData: selectAlarmStatus,
                              pickerStyle: DownBoxStyle(themeInfo, "告警类型")
                                  .builder(), onConfirm: (p) {
                            setState(() {
                              selectAlarmStatus = p["name"];
                              par["alarmType"] =
                                  p["code"] == 999 ? "" : p["code"];
                            });
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: ST.setw(10), vertical: ST.seth(15)),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                              border: Border.all(
                                  color: SystemConfig.borderColor,
                                  width: 1,
                                  style: BorderStyle.solid)),
                          child: Text(
                              "${selectAlarmStatus == null ? "请选择告警类型" : selectAlarmStatus}",
                              style:
                                  TextStyle(fontSize: SystemConfig.fs_Xsmall)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(
                    horizontal: ST.setw(30), vertical: ST.seth(10)),
                child: Row(
                  children: [
                    Text("处理状态：",
                        style: TextStyle(fontSize: SystemConfig.fs_content3)),
                    Expanded(
                      child: InkWell(
                        onTap: () async {
                          PickerWidget.showNewSinglePicker(context,
                              data: alarmStateSourceData,
                              selectData: selectHandleStatus,
                              pickerStyle: DownBoxStyle(themeInfo, "处理状态")
                                  .builder(), onConfirm: (p) {
                            setState(() {
                              selectHandleStatus = p["name"];
                              par["status"] = p["code"] >= 999 ? "" : p["code"];
                            });
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: ST.setw(10), vertical: ST.seth(15)),
                          alignment: Alignment.centerLeft,
                          decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2)),
                              border: Border.all(
                                  color: SystemConfig.borderColor,
                                  width: 1,
                                  style: BorderStyle.solid)),
                          child: Text(
                              "${selectHandleStatus == null ? "请选择处理状态" : selectHandleStatus}",
                              style:
                                  TextStyle(fontSize: SystemConfig.fs_Xsmall)),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: ST.setw(30)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      child: MaterialButton(
                          color: Colors.orangeAccent,
                          onPressed: () {
                            setState(() {
                              // 还原请求参数
                              par["createTimeStart"] = "";
                              par["createTimeEnd"] = "";
                              par["status"] = "0";
                              par["alarmType"] = null;
                              par["type"] = null;

                              // 还原显示状态
                              selectHandleStatus = "未处理";
                              selectAlarmStatus = "全部";
                              selectDeviceType = "全部";
                            });
                          },
                          child: Text('重置',
                              style: TextStyle(color: Colors.white))),
                    ),
                    SizedBox(width: ST.setw(30)),
                    Container(
                      child: MaterialButton(
                          color: SystemConfig.themeColor,
                          onPressed: () {
                            Navigator.of(context).pop();

                            // 条件修改后才执行获取数据操作
                            if (Contrast.contrastData(par)) {
                              setState(() {
                                pageData = [];
                                falg = true;
                                par["page"] = 1;
                              });

                              // 获取数据
                              initPage(context, isShowLoading: true);
                            }
                          },
                          child: Text("确认",
                              style: TextStyle(color: Colors.white))),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        scaffold: Scaffold(
            appBar: AppBarWidget("告警信息").build(context),
            body: Container(
              width: double.infinity,
              child: Stack(
                children: [
                  isCompleteLoad
                      ? Container(
                          margin: EdgeInsets.only(
                              top: model.networkstate
                                  ? ST.seth(90)
                                  : ST.seth(76)),
                          child: SmartRefresher(
                            enablePullDown: false,
                            enablePullUp: true,
                            footer: CustomFooter(
                              builder: (BuildContext context, LoadStatus mode) {
                                Widget body;
                                if (mode == LoadStatus.idle) {
                                  body = LoadStateDesc('上拉加载更多...');
                                } else if (mode == LoadStatus.loading) {
                                  body = LoadStateDesc("正在玩命加载 . . .",
                                      isLoadComponent: true);
                                } else if (mode == LoadStatus.failed) {
                                  body = LoadStateDesc('加载失败！点击重试！');
                                } else if (mode == LoadStatus.canLoading) {
                                  body = LoadStateDesc('请松开触碰,加载更多...');
                                } else {
                                  body = LoadStateDesc('没有更多数据了...',
                                      isLoadComponent: false);
                                }
                                return Container(
                                  child: Center(child: body),
                                );
                              },
                            ),
                            controller: _refreshController,
                            onLoading: _onLoading,
                            child: ListView.builder(
                              itemCount: pageData.length, //10
                              itemBuilder: (BuildContext context, int index) {
                                return Container(
                                  alignment: Alignment.center,
                                  padding: EdgeInsets.symmetric(
                                      vertical: ST.seth(10)),
                                  decoration: BoxDecoration(
                                      color: Theme.of(context).backgroundColor,
                                      border: Border(
                                          bottom: BorderSide(
                                              color:
                                                  SystemConfig.borderColor))),
                                  child: Row(
                                    children: [
                                      RowItem(160, pageData[index].createTime),
                                      RowItem(
                                          160,
                                          pageData[index]
                                              .equipmentPositionName),
                                      RowItem(160, pageData[index].sourceName),
                                      RowItem(
                                          150,
                                          pageData[index]
                                              .alarmStatusName
                                              .split("-")[1]),
                                      RowItemStatus(
                                          120,
                                          analysisCode(pageData[index].status,
                                                  alarmDisplayStateSourceData)[
                                              "name"],
                                          pageData[index].status)
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),
                        )
                      : NoData(),
                  networkstate
                      ? Positioned(
                          right: 0,
                          bottom: ST.seth(120),
                          child: Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(8),
                                bottomLeft: Radius.circular(8),
                              ),
                              color: Color.fromRGBO(159, 159, 159, .8),
                            ),
                            child: IconButton(
                              color: Colors.white,
                              icon:
                                  Icon(CustomIcons.query, color: Colors.white),
                              onPressed: () => CreateInnerDrawerKey.toggle(),
                            ),
                          ),
                        )
                      : SizedBox.shrink(),
                  componentState == null
                      ? TitlePositioned()
                      : SizedBox.shrink(),
                  componentState == null
                      ? SizedBox.shrink()
                      : Positioned(
                          top: 0,
                          left: 0,
                          right: 0,
                          child: FixedTopWidget(componentState),
                        )
                ],
              ),
            )),
      );
    });
  }

  /// 获取当前主题
  Future initThemeType() async {
    String lsThemeType = await LocalStorage.getStringItem("themeContext");
    if (lsThemeType == "ThemeType.dark") {
      setState(() {
        themeInfo = true; //黑夜
      });
    } else {
      setState(() {
        themeInfo = false; //高亮
      });
    }
  }

  /// * 上拉加载更多
  void _onLoading() async {
    if (!falg) {
      // 关闭加载更多事件
      _refreshController.loadNoData();
    } else {
      // 拉下后请求数据
      initPage(context);
    }
  }

  /// 初始化页面
  /// * [context] 必填|上下文
  void initPage(BuildContext context, {bool isShowLoading = false}) async {
    // 获取告警类型
    alarmType = await OptionTypeVM().analysisAlarmType(context);

    // 获取列表列表
    deviceType = await OptionTypeVM().analysisDeviceType(context);

    // 读取台区信息  equipmentInfo["equipmentId"]
    equipmentInfo =
        json.decode(await LocalStorage.getStringItem("equipmentInfo"));

    par["equipmentId"] = equipmentInfo["equipmentId"];

    // 接收后台返回的数据
    AlarmBean result = await AlarmVM()
        .getAlarmInfo(context, par, isShowLoading: isShowLoading);

    // 完成加载更多通知
    _refreshController.loadComplete();

    // 防止进入后快速返回而导致的异常
    if (!this.mounted) return;

    // 验证返回的数据
    if (result != null) {
      // 解构数据中的list
      setState(() {
        pageData.addAll(result.list);
      });

      // 控制显示数据内容
      if (result.list.length > 0 && pageData.length > 0) {
        setState(() {
          isCompleteLoad = true;
          par["page"] = par["page"] + 1;
        });
      }

      // 检查是否还有数据未请求
      if (pageData.length >= result.total) {
        _refreshController.loadNoData();
        setState(() {
          falg = false;
        });
      }
    } else {
      // 提示没有更多数据了
      _refreshController.loadNoData();
    }
  }
}
